<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频管理测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            background-color: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        h1, h2 {
            color: #333;
        }

        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }

        button:hover {
            background-color: #45a049;
        }

        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        button.delete {
            background-color: #f44336;
        }

        button.delete:hover {
            background-color: #d32f2f;
        }

        button.refresh {
            background-color: #2196F3;
        }

        button.refresh:hover {
            background-color: #1976D2;
        }

        .video-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .video-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            background-color: #fafafa;
        }

        .video-card h3 {
            margin-top: 0;
            color: #333;
        }

        .video-info {
            margin: 5px 0;
            font-size: 14px;
            color: #666;
        }

        .status {
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }

        .status.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .status.info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            margin: 20px 0;
            background-color: #fafafa;
        }

        .upload-area.dragover {
            border-color: #4CAF50;
            background-color: #e8f5e9;
        }

        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }

        .progress-fill {
            height: 100%;
            background-color: #4CAF50;
            width: 0%;
            transition: width 0.3s;
        }

        .file-info {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin: 10px 0;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 800px;
            border-radius: 8px;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover,
        .close:focus {
            color: black;
        }

        .video-player-container {
            width: 100%;
            height: 0;
            padding-bottom: 56.25%; /* 16:9 宽高比 */
            position: relative;
        }

        .video-player-container video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
<h1>视频管理测试页面</h1>

<div class="container">
    <h2>视频上传</h2>
    <div class="upload-area" id="uploadArea">
        <p>拖拽文件到此处或点击选择文件</p>
        <input type="file" id="fileInput" accept="video/*" style="display: none;">
        <button id="selectFileBtn">选择文件</button>
    </div>
    <div id="fileInfo" class="file-info" style="display: none;"></div>
    <button id="uploadBtn" disabled>上传视频</button>
    <div class="progress-bar" id="progressBar" style="display: none;">
        <div class="progress-fill" id="progressFill"></div>
    </div>
    <div id="uploadProgressText"></div>
</div>

<div class="container">
    <h2>视频列表</h2>
    <button id="refreshBtn" class="refresh">刷新列表</button>
    <button id="prevBtn" disabled>上一页</button>
    <button id="nextBtn" disabled>下一页</button>
    <span id="pageInfo"></span>
    <div id="status" class="status" style="display: none;"></div>
    <div class="video-list" id="videoList"></div>
</div>

<!-- 视频播放模态框 -->
<div id="videoModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2 id="modalVideoTitle">视频播放</h2>
        <div class="video-player-container">
            <video id="videoPlayer" controls>
                您的浏览器不支持视频播放。
            </video>
        </div>
    </div>
</div>

<script>
    // 全局变量
    const BASE_URL = 'http://localhost:8080/api';
    let currentFile = null;
    let currentPage = 1;
    let totalPages = 1;
    let totalVideos = 0;
    let currentVideoId = null; // 当前播放的视频ID
    let currentUserId = 1; // 示例用户ID，实际应用中应该从登录信息获取
    let progressSaveInterval = null; // 进度保存定时器

    // DOM 元素
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    const selectFileBtn = document.getElementById('selectFileBtn');
    const fileInfo = document.getElementById('fileInfo');
    const uploadBtn = document.getElementById('uploadBtn');
    const progressBar = document.getElementById('progressBar');
    const progressFill = document.getElementById('progressFill');
    const uploadProgressText = document.getElementById('uploadProgressText');
    const refreshBtn = document.getElementById('refreshBtn');
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');
    const pageInfo = document.getElementById('pageInfo');
    const status = document.getElementById('status');
    const videoList = document.getElementById('videoList');
    const videoModal = document.getElementById('videoModal');
    const videoPlayer = document.getElementById('videoPlayer');
    const modalVideoTitle = document.getElementById('modalVideoTitle');
    const closeModal = document.getElementsByClassName('close')[0];

    // 事件监听器
    selectFileBtn.addEventListener('click', () => fileInput.click());
    fileInput.addEventListener('change', handleFileSelect);
    uploadBtn.addEventListener('click', uploadVideo);
    refreshBtn.addEventListener('click', () => loadVideos(currentPage));
    prevBtn.addEventListener('click', () => loadVideos(currentPage - 1));
    nextBtn.addEventListener('click', () => loadVideos(currentPage + 1));

    // 模态框关闭事件
    closeModal.addEventListener('click', () => {
        // 先停止保存进度（这会保存最后一次进度）
        stopProgressSaving();

        // 再暂停和清理视频
        videoModal.style.display = 'none';
        videoPlayer.pause();
        videoPlayer.src = '';
        currentVideoId = null;
    });

    window.addEventListener('click', (event) => {
        if (event.target == videoModal) {
            // 先停止保存进度（这会保存最后一次进度）
            stopProgressSaving();

            // 再暂停和清理视频
            videoModal.style.display = 'none';
            videoPlayer.pause();
            videoPlayer.src = '';
            currentVideoId = null;
        }
    });


    // 拖拽上传事件
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });

    uploadArea.addEventListener('dragleave', () => {
        uploadArea.classList.remove('dragover');
    });

    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        if (e.dataTransfer.files.length) {
            fileInput.files = e.dataTransfer.files;
            handleFileSelect({target: fileInput});
        }
    });

    // 处理文件选择
    function handleFileSelect(event) {
        const file = event.target.files[0];
        if (!file) return;

        currentFile = file;
        showFileInfo(file);
        uploadBtn.disabled = false;
    }

    // 显示文件信息
    function showFileInfo(file) {
        fileInfo.style.display = 'block';
        fileInfo.innerHTML = `
                <strong>文件名:</strong> ${file.name}<br>
                <strong>文件大小:</strong> ${formatFileSize(file.size)}<br>
                <strong>文件类型:</strong> ${file.type || '未知'}<br>
            `;
    }

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 更新状态显示
    function updateStatus(message, type = 'info') {
        status.textContent = message;
        status.className = 'status ' + type;
        status.style.display = 'block';

        // 3秒后自动隐藏成功或信息状态
        if (type === 'success' || type === 'info') {
            setTimeout(() => {
                status.style.display = 'none';
            }, 3000);
        }
    }

    // 更新进度显示
    function updateProgress(percent) {
        progressBar.style.display = 'block';
        progressFill.style.width = percent + '%';
        uploadProgressText.textContent = `上传进度: ${percent.toFixed(2)}%`;
    }

    // 播放视频
    async function playVideo(id, title) {
        try {
            // 获取视频播放URL
            const response = await fetch(`${BASE_URL}/videos/${id}/play-url`);

            if (!response.ok) {
                throw new Error('获取播放URL失败: ' + response.statusText);
            }

            const result = await response.json();
            const playUrl = result.data;

            // 设置模态框标题
            modalVideoTitle.textContent = title;

            // 设置视频源
            videoPlayer.src = playUrl;

            // 保存当前视频ID
            currentVideoId = id;

            // 显示模态框
            videoModal.style.display = 'block';

            // 等待视频可以播放
            videoPlayer.addEventListener('canplay', async () => {
                // 获取用户的播放进度
                await loadPlaybackProgress(id);

                // 开始播放
                const playPromise = videoPlayer.play();

                if (playPromise !== undefined) {
                    playPromise.then(() => {
                        // 自动播放开始
                        console.log('视频开始播放');
                        // 启动定时保存播放进度
                        startProgressSaving();
                    }).catch(error => {
                        console.log('自动播放被阻止: ', error);
                        // 即使自动播放被阻止，也启动进度保存
                        startProgressSaving();
                    });
                }
            }, {once: true});

        } catch (error) {
            updateStatus('播放失败: ' + error.message, 'error');
        }
    }


    // 获取用户的播放进度
    async function loadPlaybackProgress(videoId) {
        try {
            const response = await fetch(`${BASE_URL}/videos/${videoId}/progress?userId=${currentUserId}`);

            if (!response.ok) {
                console.warn('获取播放进度失败: ' + response.statusText);
                return;
            }

            const result = await response.json();

            // 如果有播放进度记录，则跳转到对应位置
            if (result.code === 200 && result.data) {
                const progress = result.data.progress;
                if (progress > 0) {
                    videoPlayer.currentTime = progress;
                    updateStatus(`已从 ${formatDuration(progress)} 处继续播放`, 'info');
                }
            }
        } catch (error) {
            console.warn('获取播放进度失败: ' + error.message);
        }
    }

    // 启动定时保存播放进度
    function startProgressSaving() {
        // 清除之前的定时器
        if (progressSaveInterval) {
            clearInterval(progressSaveInterval);
        }

        // 每30秒保存一次播放进度
        progressSaveInterval = setInterval(savePlaybackProgress, 30000);
    }

    // 保存播放进度
    async function savePlaybackProgress() {
        // 只有在有当前视频ID时才保存进度
        if (!currentVideoId) {
            return;
        }

        // 确保视频已开始播放且有有效的currentTime
        if (isNaN(videoPlayer.currentTime) || videoPlayer.currentTime < 0) {
            console.warn('无效的播放时间: ' + videoPlayer.currentTime);
            return;
        }

        const progress = Math.floor(videoPlayer.currentTime);
        const duration = Math.floor(videoPlayer.duration) || 0;

        // 添加调试日志
        console.log('保存播放进度: progress=' + progress + ', duration=' + duration +
            ', currentTime=' + videoPlayer.currentTime +
            ', paused=' + videoPlayer.paused +
            ', ended=' + videoPlayer.ended);

        try {
            const response = await fetch(`${BASE_URL}/videos/${currentVideoId}/progress`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `userId=${currentUserId}&progress=${progress}&duration=${duration}`
            });

            if (!response.ok) {
                console.warn('保存播放进度失败: ' + response.statusText);
            } else {
                const result = await response.json();
                console.log('播放进度保存成功: ' + progress + '秒', result);
            }
        } catch (error) {
            console.warn('保存播放进度失败: ' + error.message);
        }
    }


    // 停止保存播放进度
    function stopProgressSaving() {
        // 先立即保存一次进度（在清除定时器之前）
        if (currentVideoId) {
            savePlaybackProgress();
        }

        if (progressSaveInterval) {
            clearInterval(progressSaveInterval);
            progressSaveInterval = null;
        }
    }


    // 上传视频
    async function uploadVideo() {
        if (!currentFile) {
            updateStatus('请先选择文件', 'error');
            return;
        }

        const formData = new FormData();
        formData.append('file', currentFile);

        try {
            updateStatus('正在上传视频...', 'info');
            uploadBtn.disabled = true;

            const xhr = new XMLHttpRequest();

            // 监听上传进度
            xhr.upload.addEventListener('progress', (e) => {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    updateProgress(percentComplete);
                }
            });

            // 监听请求完成
            xhr.addEventListener('load', () => {
                if (xhr.status >= 200 && xhr.status < 300) {
                    const response = JSON.parse(xhr.responseText);
                    updateStatus('视频上传成功!', 'success');
                    updateProgress(100);
                    loadVideos(1); // 上传成功后刷新列表
                    // 重置文件选择
                    fileInput.value = '';
                    fileInfo.style.display = 'none';
                    currentFile = null;
                    uploadBtn.disabled = true;
                } else {
                    updateStatus('上传失败: ' + xhr.statusText, 'error');
                }
            });

            xhr.addEventListener('error', () => {
                updateStatus('上传失败: 网络错误', 'error');
                uploadBtn.disabled = false;
            });

            xhr.open('POST', `${BASE_URL}/videos/upload`);
            xhr.send(formData);

        } catch (error) {
            updateStatus('上传失败: ' + error.message, 'error');
            uploadBtn.disabled = false;
        }
    }

    // 加载视频列表
    async function loadVideos(page = 1) {
        try {
            updateStatus('正在加载视频列表...', 'info');
            const response = await fetch(`${BASE_URL}/videos?pageNum=${page}&pageSize=6`);

            if (!response.ok) {
                throw new Error('加载视频列表失败: ' + response.statusText);
            }

            const result = await response.json();
            const data = result.data;

            currentPage = data.current;
            totalPages = data.pages;
            totalVideos = data.total;

            renderVideoList(data.records);
            updatePagination();
            updateStatus('视频列表加载成功', 'success');

        } catch (error) {
            updateStatus('加载视频列表失败: ' + error.message, 'error');
        }
    }

    // 渲染视频列表
    function renderVideoList(videos) {
        if (videos.length === 0) {
            videoList.innerHTML = '<p>暂无视频</p>';
            return;
        }

        videoList.innerHTML = videos.map(video => `
                <div class="video-card" data-id="${video.id}">
                    <h3>${video.title}</h3>
                    <div class="video-info">
                        <p><strong>文件名:</strong> ${video.fileName}</p>
                        <p><strong>文件大小:</strong> ${formatFileSize(video.fileSize)}</p>
                        <p><strong>时长:</strong> ${formatDuration(video.duration)}</p>
                        <p><strong>上传时间:</strong> ${new Date(video.uploadTime).toLocaleString()}</p>
                    </div>
                    <button onclick="playVideo(${video.id}, '${video.title}')">播放</button>
                    <button class="delete" onclick="deleteVideo(${video.id}, '${video.title}')">删除</button>
                </div>
            `).join('');
    }

    // 格式化时长
    function formatDuration(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins}:${secs.toString().padStart(2, '0')}`;
    }

    // 更新分页信息
    function updatePagination() {
        pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页（总计 ${totalVideos} 个视频）`;
        prevBtn.disabled = currentPage <= 1;
        nextBtn.disabled = currentPage >= totalPages;
    }

    // 删除视频
    async function deleteVideo(id, title) {
        if (!confirm(`确定要删除视频 "${title}" 吗？`)) {
            return;
        }

        try {
            updateStatus(`正在删除视频 "${title}"...`, 'info');
            const response = await fetch(`${BASE_URL}/videos/${id}`, {
                method: 'DELETE'
            });

            if (!response.ok) {
                throw new Error('删除失败: ' + response.statusText);
            }

            updateStatus(`视频 "${title}" 删除成功`, 'success');
            loadVideos(currentPage); // 刷新当前页

        } catch (error) {
            updateStatus('删除失败: ' + error.message, 'error');
        }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
        loadVideos(1);
    });

    // 模态框关闭事件
    closeModal.addEventListener('click', () => {
        videoModal.style.display = 'none';
        videoPlayer.pause();
        videoPlayer.src = '';
        stopProgressSaving(); // 停止保存进度
        currentVideoId = null;
    });

    window.addEventListener('click', (event) => {
        if (event.target == videoModal) {
            videoModal.style.display = 'none';
            videoPlayer.pause();
            videoPlayer.src = '';
            stopProgressSaving(); // 停止保存进度
            currentVideoId = null;
        }
    });

    // 将函数暴露到全局作用域，供HTML中的onclick使用
    window.playVideo = playVideo;
    window.deleteVideo = deleteVideo;
</script>
</body>
</html>
